#include "BluetoothConnection.h"

#include "SocketException.h"
#include "Exception.h"
#include "WinException.h"
#include "BipBuffer.h"
#include "BufferedReader.h"


using namespace std;

// constructor to create a BluetoothConnection object from an ::accept() call
BluetoothConnection::BluetoothConnection(SOCKADDR_BTH address, SOCKET client)
	: mSocket(client)
	, mAddress(address)
{
	//setsockopt(mSocket, , SO_RCVTIMEO, 

	/*
	fd_set s;
	s.fd_array[0] = mSocket;
	s.fd_count = 1;
	timeval t;
	t.tv_sec = 1;
	::select(0, &s,NULL,NULL, &t);
	*/

}

std::string BluetoothConnection::toString() {
	return string("BluetoothConnection ") + to_string(mSocket);
}

	


BluetoothConnection::BluetoothConnection() 
	:mSocket(INVALID_SOCKET)
	,mAddress()
{}


void BluetoothConnection::close() {
	// close connection, causing ::recv() call to return
	if (::closesocket(mSocket) 
		== SOCKET_ERROR) throw SocketException(_T("BluetoothConnection::close() : closesocket()"), WSAGetLastError());
	mSocket = INVALID_SOCKET;
}


//throws Exception, SocketException
int BluetoothConnection::read(char* buf, int bufSize) {
	printf( __FUNCTION__ "\n");
	int bytesRead;
	bytesRead = ::recv(mSocket, buf, bufSize ,0);
	// check the return value for errors
	switch(bytesRead) {
	    case 0: throw Exception("BluetoothConnection::read() : recv() : The connection has been closed");
	    case SOCKET_ERROR:
		    switch (WSAGetLastError()) {
		        case WSAEWOULDBLOCK: //break;
		        default: throw SocketException(_T("BluetoothConnection::read() : recv()"), WSAGetLastError());
			};
		default: break;
	};
	return bytesRead;
}


//throws SocketException
void BluetoothConnection::sendString( string s) {
	//printf("BluetoothConnection sending String: %s\n",s.c_str());
	if (::send(mSocket, s.c_str(), s.length(), 0) // MSG_DONTROUTE MSG_OOB
		== SOCKET_ERROR) throw SocketException(_T("BluetoothConnection::readLine(): send: "),  WSAGetLastError());
}


